import 'package:flutter_admin/api/odoo/sale_inquiry_form_odoo_api.dart';
import 'package:flutter_admin/api/odoo/sale_inquiry_product_odoo_api.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_product.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_browse_list.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_excel.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_form_dialog.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_form_edit.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_form_file/sale_inquiry_form_file_list.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_form_view.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_product_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class SaleInquiryFormList extends StatefulWidget {
  SaleInquiryFormList({Key? key}) : super(key: key);

  @override
  _SaleInquiryFormList createState() => _SaleInquiryFormList();
}

class _SaleInquiryFormList extends State<SaleInquiryFormList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  SaleInquiryForm saleInquiryForm = SaleInquiryForm();
  List<SaleInquiryForm> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');
  late List<SelectOptionVO> stateList = [];

  @override
  void initState() {
    super.initState();
    saleInquiryForm.createDateStart = Utils.getDate();
    saleInquiryForm.createDateEnd = Utils.getDate();
    saleInquiryForm.state = '0';
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      stateList = [
        SelectOptionVO(value: '0', label: "已创建"),
        SelectOptionVO(value: '2', label: "已报价"),
      ];
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '报价开始日期',
            value: saleInquiryForm.createDateStart,
            lastDate: isNotBlank(saleInquiryForm.createDateEnd)
                ? format.parse(saleInquiryForm.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleInquiryForm.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              saleInquiryForm.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '报价结束日期',
            value: saleInquiryForm.createDateEnd,
            firstDate: isNotBlank(saleInquiryForm.createDateStart)
                ? format.parse(saleInquiryForm.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleInquiryForm.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              saleInquiryForm.createDateEnd = v;
            },
          ),
          CryInput(
            width: 160,
            label: '询价单编号',
            value: saleInquiryForm.inquiryNo,
            onSaved: (v) {
              saleInquiryForm.inquiryNo = v;
            },
          ),
          CryInput(
            width: 160,
            label: '询价单位',
            value: saleInquiryForm.partnerName,
            onSaved: (v) {
              saleInquiryForm.partnerName = v;
            },
          ),
          CryInput(
            width: 140,
            label: '业务员',
            value: saleInquiryForm.userName,
            onSaved: (v) {
              saleInquiryForm.userName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: saleInquiryForm.name,
            onSaved: (v) {
              saleInquiryForm.name = v;
            },
          ),
          CrySelect(
            width: 140,
            label: '状态',
            dataList: stateList,
            value: saleInquiryForm.state,
            onSaved: (v) => {saleInquiryForm.state = v},
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('状态')),
        DataColumn(label: Text('询价单编号')),
        DataColumn(label: Text('报价单位')),
        DataColumn(label: Text('业务员')),
        DataColumn(label: Text('事业部')),
        DataColumn(label: Text('电话')),
        DataColumn(label: Text('邮箱')),
        DataColumn(label: Text('询价单位')),
        DataColumn(label: Text('项目名称')),
        DataColumn(label: Text('客户性质')),
        DataColumn(label: Text('付款方式')),
        DataColumn(label: Text('到货地点')),
        DataColumn(label: Text('是否有目标价')),
        DataColumn(label: Text('合计(元)')),
        DataColumn(label: Text('费用合计（元）')),
        DataColumn(label: Text('毛利润（元）')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        SaleInquiryForm saleInquiryForm = SaleInquiryForm.fromMap(m);
        return [
          DataCell(Text(saleInquiryForm.state == '2'
              ? '已报价'
              : saleInquiryForm.state == '0'
                  ? '已创建'
                  : '--')),
          DataCell(Text(saleInquiryForm.inquiryNo ?? '--')),
          DataCell(Text(saleInquiryForm.companyName ?? '--')),
          DataCell(Text(saleInquiryForm.userName ?? '--')),
          DataCell(Text(saleInquiryForm.deptName ?? '--')),
          DataCell(Text(saleInquiryForm.phone ?? '--')),
          DataCell(Text(saleInquiryForm.email ?? '--')),
          DataCell(Text(saleInquiryForm.partnerName ?? '--')),
          DataCell(Text(saleInquiryForm.projectName ?? '--')),
          DataCell(Text(saleInquiryForm.customerNature ?? '--')),
          DataCell(Text(saleInquiryForm.paymentMethod ?? '--')),
          DataCell(Text(saleInquiryForm.arrivalPlace ?? '--')),
          DataCell(Text(saleInquiryForm.isTargetprice == '1'
              ? '是'
              : saleInquiryForm.isTargetprice == '0'
                  ? '否'
                  : '--')),
          DataCell(Text(saleInquiryForm.sum ?? '--')),
          DataCell(Text(saleInquiryForm.amountTotal != null
              ? saleInquiryForm.amountTotal.toString()
              : '--')),
          DataCell(Text(saleInquiryForm.grossProfit != null
              ? saleInquiryForm.grossProfit.toString()
              : '--')),
          DataCell(Text(saleInquiryForm.createUid ?? '--')),
          DataCell(Text(Utils.timeUTC(saleInquiryForm.createDate ?? '--'))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(
            context, () => _edit(null)),
        CryButtons.edit(
            context,
            (selectedList.length != 1 || saleInquiryForm.state == '2')
                ? null
                : () => _edit(selectedList[0])),
        CryButtons.delete(
            context,
            (selectedList.length < 1 || saleInquiryForm.state == '2')
                ? null
                : () => _delete(selectedList)),
        CryButton(
          label: "产品明细",
          iconData: Icons.view_headline,
          onPressed: (selectedList.length == 1 && saleInquiryForm.state == '2')
              ? () => _openDetail(selectedList[0])
              : null,
        ),
        CryButton(
          label: "复制",
          iconData: Icons.copy,
          onPressed:
              selectedList.length == 1 ? () => _copy(selectedList[0]) : null,
        ),
        CryButton(
          label: "确认",
          iconData: Icons.view_headline,
          onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
              ? () => _browse(selectedList[0])
              : null,
        ),
        CryButton(
          label: "查看",
          iconData: Icons.view_headline,
          onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
              ? () => _view(selectedList[0])
              : null,
        ),
        CryButton(
          label: "导出",
          onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
              ? () => _generateExcel(selectedList[0])
              : null,
          iconData: Icons.import_export_outlined,
        ),
        // CryButton(
        //   label: "附件上传",
        //   onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
        //       ? () => _upload(selectedList[0])
        //       : null,
        //   iconData: Icons.upload_rounded,
        // ),
        // CryButton(
        //   label: "附件下载",
        //   onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
        //       ? () => _download(selectedList[0])
        //       : null,
        //   iconData: Icons.file_download,
        // ),
        CryButton(
          label: "附件",
          onPressed: (selectedList.length == 1 && saleInquiryForm.state == '0')
              ? () => _dmsFile(selectedList[0])
              : null,
          iconData: Icons.view_agenda_rounded,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  // 询价单编号
  _dmsFile(SaleInquiryForm saleInquiryForm) {
    Utils.fullscreenDialog(
        SaleInquiryFormFileList(saleInquiryForm: saleInquiryForm));
  }

  // _upload(SaleInquiryForm saleInquiryForm) {
  //   showDialog(
  //     context: context,
  //     builder: (BuildContext context) => Dialog(
  //       child: SaleInquiryFormFileUpload(
  //         documentno: saleInquiryForm.inquiryNo,
  //       ),
  //     ),
  //   ).then((v) {
  //     if (v != null) {
  //       _query();
  //     }
  //   });
  // }

  // _download(SaleInquiryForm saleInquiryForm) {
  //   showDialog(
  //     context: context,
  //     builder: (BuildContext context) => Dialog(
  //       child: SaleInquiryFormFileDownLoad(
  //         documentno: saleInquiryForm.inquiryNo,
  //       ),
  //     ),
  //   ).then((v) {
  //     if (v != null) {
  //       _query();
  //     }
  //   });
  // }

  _generateExcel(SaleInquiryForm saleInquiryForm) async {
    SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct();
    saleInquiryProduct.inquiryId = saleInquiryForm.id;
    ResponseBodyApi responseBodyApi =
        await SaleInquiryProductOdooApi.page(data: {
      'type': 'browse',
      "domainList": saleInquiryProduct.toDomainList(),
    });
    List<SaleInquiryProduct> selectedList = [];
    if (responseBodyApi.success!) {
      selectedList = responseBodyApi.data
              .map<SaleInquiryProduct>((e) => SaleInquiryProduct.fromMap(e))
              .toList() ??
          [];
      SaleInquiryExcel.generateExcel(
          fileName: "询价信息表",
          dataForm: saleInquiryForm,
          datatable: selectedList);
    }
  }

  _copy(SaleInquiryForm? saleInquiryForm) async {
    saleInquiryForm!.id = null;
    SaleInquiryFormOdooApi.copy(saleInquiryForm.toOdooMap())
        .then((ResponseBodyApi res) {
      if (!res.success!) {
        return;
      }
      _query();
      CryUtils.message('复制成功');
    });
  }

  _openDetail(SaleInquiryForm saleInquiryForm) {
    Utils.fullscreenDialog(
        SaleInquiryProductList(saleInquiryForm: saleInquiryForm));
  }

  _browse(SaleInquiryForm? saleInquiryForm) {
    final subscription = EventBus.getSubscriber()
        .where((event) => event["type"] == "form:saved")
        .listen(null);
    subscription.onData((data) {
      subscription.cancel();
      _query();
    });
    Utils.fullscreenDialog(
        SaleInquiryBrowseList(saleInquiryForm: saleInquiryForm));
  }

  _view(SaleInquiryForm? saleInquiryForm) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryFormView(
          saleInquiryForm: saleInquiryForm,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _edit(SaleInquiryForm? saleInquiryForm) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryFormEdit(
          saleInquiryForm: saleInquiryForm,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (saleInquiryForm == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    saleInquiryForm = SaleInquiryForm();
    formKey.currentState!.reset();
    saleInquiryForm.createDateStart = Utils.getDate();
    saleInquiryForm.createDateEnd = Utils.getDate();
    saleInquiryForm.state = '0';
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    // var filter = {};
    // if (saleInquiryForm.partnerName != null &&
    //     saleInquiryForm.partnerName != "") {
    //   filter = {
    //     "res.partner": [
    //       'id',
    //       ['name', 'like', '%${saleInquiryForm.partnerName}%']
    //     ]
    //   };
    // }
    ResponseBodyApi responseBodyApi = await SaleInquiryFormOdooApi.page(
        data: {"page": page, "domainList": saleInquiryForm.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<SaleInquiryForm> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await SaleInquiryFormOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryFormDialog(),
      ),
    ).then((v) {
      if (v != null) {
        saleInquiryForm = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<SaleInquiryForm>((e) => SaleInquiryForm.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.dmsFile) {
          _openDetail(selectedList[0]);
        } else if (v == OperationType.handle) {
          _browse(selectedList[0]);
        } else if (v == OperationType.dmsFile) {
          _dmsFile(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: saleInquiryForm.state == '0',
          child: ListTile(
            leading: const Icon(Icons.add),
            enabled: saleInquiryForm.state == '0',
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1 && saleInquiryForm.state == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && saleInquiryForm.state == '0',
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0 && saleInquiryForm.state == '0',
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0 && saleInquiryForm.state == '0',
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('产品明细'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length == 1 && saleInquiryForm.state == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && saleInquiryForm.state == '0',
            title: Text('确认'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('附件'),
          ),
        ),
      ],
    );
  }
}
